package com.xinqi.modules.databank.v2.service.video.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.xinqi.common.base.response.R;
import com.xinqi.common.core.enums.*;
import com.xinqi.common.core.utils.MessageUtils;
import com.xinqi.common.satoken.utils.LoginHelper;
import com.xinqi.common.base.dto.CommonFileDTO;
import com.xinqi.common.base.enums.YesNoNumberEnum;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.utils.json.JSON;
import com.xinqi.modules.course.chapter.dto.client.CourseChapterClient;
import com.xinqi.modules.course.clazz.client.ClassStudentClient;
import com.xinqi.modules.course.clazz.dto.rsp.ClassStudentResultDTO;
import com.xinqi.modules.databank.dto.req.*;
import com.xinqi.modules.databank.dto.req.question.CommonVideoPartDTO;
import com.xinqi.modules.databank.dto.rsp.ResourceResponseDTO;
import com.xinqi.modules.databank.dto.rsp.ResourceStatisticsDTO;
import com.xinqi.modules.databank.dto.rsp.ResourceStatisticsStatsDTO;
import com.xinqi.modules.databank.v2.convert.CourseResourceConvert;
import com.xinqi.modules.databank.v2.convert.CourseResourcePartConvert;
import com.xinqi.modules.databank.v2.domain.CourseResourceEntity;
import com.xinqi.modules.databank.v2.domain.CourseResourcePartEntity;
import com.xinqi.modules.databank.v2.domain.CourseResourceStudentLogEntity;
import com.xinqi.modules.databank.v2.manager.CourseResourceBaseManager;
import com.xinqi.modules.databank.v2.manager.CourseResourcePartManager;
import com.xinqi.modules.databank.v2.manager.CourseResourceStudentLogManager;
import com.xinqi.modules.databank.v2.util.MathUtils;
import com.xinqi.modules.databank.v2.service.assistant.AssistantListen;
import com.xinqi.modules.databank.v2.service.common.CourseResourceBaseService;
import com.xinqi.modules.databank.v2.service.part.ResourcePartService;
import com.xinqi.modules.databank.v2.service.student.ResourceStudentLogService;
import com.xinqi.modules.databank.v2.service.sync.CourseResourceSyncService;
import com.xinqi.modules.databank.v2.service.video.CourseResourceVideoService;
import com.xinqi.modules.databank.v2.util.ResourceUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 资料库-资料-方法
 * @author dzy
 */
@Service
@RequiredArgsConstructor
public class CourseResourceVideoServiceImpl implements CourseResourceVideoService {

    private final CourseResourceConvert courseResourceConvert;

    private final IdentifierGenerator identifierGenerator;

    private final CourseResourceBaseManager courseResourceBaseManager;
    @Lazy
    private final CourseResourceBaseService courseResourceBaseService;


    private final CourseResourcePartConvert resourcePartConvert;
    private final CourseResourcePartManager resourcePartManager;
    private final ResourcePartService resourcePartService;

    private final CourseResourceStudentLogManager resourceStudentLogManager;
    @Lazy
    private final ResourceStudentLogService resourceStudentLogService;

    @Lazy
    private final CourseChapterClient courseChapterClient;

    private final CourseResourceSyncService resourceSyncService;

    private final AssistantListen assistantListen;

    @Lazy
    private final ClassStudentClient classStudentClient;

    /**
     * 新增 互动视频
     * @param videoResource 互动视频添加对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addResource(CourseResourceVideoCreateDTO videoResource) {

        // 校验文件是否上传文件
        CommonErrors.BAD_REQUEST.check(CollectionUtils.isNotEmpty(videoResource.getVideoUrls()),MessageUtils.message("course.file.is.not.blank"));

        // 转换成互动视频创建对象
        CourseResourceCreateDTO resource = courseResourceConvert.videoCreate(videoResource);

        // 添加创建用户
        resource.setUserId(LoginHelper.getUserId());

        //权限校验
        List<ClassRoleEnum> classRoles = new ArrayList<>();
        classRoles.add(ClassRoleEnum.TEACHER);
        classRoles.add(ClassRoleEnum.ASSISTANT);
        classStudentClient.checkRole(resource.getClassId(), LoginHelper.getUserId(), classRoles);

        // 转换资料库实体
        CourseResourceEntity entity = courseResourceConvert.create(resource);
        entity.setVideos(JSON.stringify(videoResource.getVideoUrls()));

        // 设置类型
        entity.setContentType(CourseContentTypeEnum.INTERACTIVE_VIDEO.getCode());

        // 设置发布状态
        ResourceUtil.checkTiming(entity);

        // 校验是否是定时发布
        ResourceUtil.checkTime(entity);

        courseResourceBaseManager.save(entity);

        // 保存答题信息
        this.saveQuestions(videoResource.getParts(), entity.getVideos(), entity.getId());

        // 发布状态 同步信息
        if (Objects.equals(YesNoNumberEnum.YES.getCode(), entity.getStatus())) {
            // 同步更新相关数据
            this.syncResourceInfo(entity);
        }

    }


    /**
     * 修改 互动视频
     * @param videoResource 互动视频新对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateResource(CourseResourceVideoUpdateDTO videoResource) {

        // 校验互动视频是否存在
        CourseResourceEntity old = Optional.ofNullable(courseResourceBaseManager.getById(videoResource.getId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));

        // 已发布只可以更新结束时间
        if (Objects.equals(YesNoNumberEnum.YES.getCode(), old.getStatus())) {
            CourseResourceEntity updateEntity = new CourseResourceEntity();
            updateEntity.setId(old.getId());
            updateEntity.setEndTime(videoResource.getEndTime());
            courseResourceBaseManager.updateById(updateEntity);
            return;
        }

        // 校验文件是否有上传文件
        CommonErrors.BAD_REQUEST.check(CollectionUtils.isNotEmpty(videoResource.getVideoUrls()),MessageUtils.message("course.file.is.not.blank"));

        // 更新创建用户
        videoResource.setUserId(LoginHelper.getUserId());

        // 更新章节信息(未设置更新章节字段为0)
        if (Objects.isNull(videoResource.getChapterId())) {
            videoResource.setChapterId(0L);
        }

        //权限校验
        List<ClassRoleEnum> classRoles = new ArrayList<>();
        classRoles.add(ClassRoleEnum.TEACHER);
        classRoles.add(ClassRoleEnum.ASSISTANT);
        classStudentClient.checkRole(old.getClassId(), LoginHelper.getUserId(), classRoles);

        CourseResourceEntity entity = courseResourceConvert.videoUpdate(videoResource);
        entity.setVideos(JSON.stringify(videoResource.getVideoUrls()));

        // 设置资料库类型 为 资料
        entity.setContentType(CourseContentTypeEnum.INTERACTIVE_VIDEO.getCode());

        // 校验定时发布
        ResourceUtil.checkTiming(entity);

        // 校验发布时间
        ResourceUtil.checkTime(entity);

        // 更新数据
        courseResourceBaseManager.updateById(entity);

        // 保存答题信息
        this.saveQuestions(videoResource.getParts(), entity.getVideos(), entity.getId());

        // 发布状态 同步信息
        if (Objects.equals(YesNoNumberEnum.YES.getCode(), entity.getStatus())) {
            // 同步更新相关数据
            this.syncResourceInfo(entity);
        }
    }

    /**
     * 一键发布 互动视频 信息
     * @param id 资料ID
     * @author dzy
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean releaseResource(Long id) {
        // 判断是否数据存在
        CourseResourceEntity entity = Optional.ofNullable(courseResourceBaseManager.getById(id))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));

        //权限校验
        List<ClassRoleEnum> classRoles = new ArrayList<>();
        classRoles.add(ClassRoleEnum.TEACHER);
        classRoles.add(ClassRoleEnum.ASSISTANT);
        classStudentClient.checkRole(entity.getClassId(), LoginHelper.getUserId(), classRoles);

        // 更新互动视频赋值
        entity.setStatus(YesNoNumberEnum.YES.getCode());
        entity.setNowRelease(1);
        entity.setReleaseTime(LocalDateTime.now());
        boolean flag = courseResourceBaseManager.updateById(entity);

        if (flag) {
            // 同步更新相关数据
            this.syncResourceInfo(entity);
        }
        return flag;
    }

    /**
     * 一键发布 互动视频 信息 V2版本
     * @param id 资料ID
     * @author dzy
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean releaseResourceV2(Long id) {
        // 判断是否数据存在
        CourseResourceEntity entity = Optional.ofNullable(courseResourceBaseManager.getById(id))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        CommonErrors.BAD_REQUEST.check(Objects.equals(YesNoNumberEnum.NO.getCode(), entity.getStatus())
            , MessageUtils.message("course.video.release.valid"));

        //权限校验
        List<ClassRoleEnum> classRoles = new ArrayList<>();
        classRoles.add(ClassRoleEnum.TEACHER);
        classRoles.add(ClassRoleEnum.ASSISTANT);
        classStudentClient.checkRole(entity.getClassId(), LoginHelper.getUserId(), classRoles);

        // 更新互动视频赋值
        entity.setStatus(YesNoNumberEnum.YES.getCode());
        entity.setTiming(YesNoNumberEnum.NO.getCode());
        entity.setNowRelease(1);
        entity.setReleaseTime(LocalDateTime.now());
        boolean flag = courseResourceBaseManager.updateById(entity);

        if (flag) {
            // 同步更新相关数据
            this.syncResourceInfo(entity);
        }
        return flag;
    }

    /**
     * 定时发布 互动视频 信息
     * @param entity 资料对象
     * @author dzy
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean timingPublish(CourseResourceEntity entity) {
        // 更新互动视频赋值
        entity.setStatus(YesNoNumberEnum.YES.getCode());
        boolean flag = courseResourceBaseManager.updatePublishById(entity.getId());
        if (flag) {
            // 同步更新相关数据
            this.syncResourceInfo(entity);
        }
        return flag;
    }

    /**
     * 同步对应的互动视频数据
     */
    public void syncResourceInfo(CourseResourceEntity entity) {
        // 同步更新主表信息
        resourceSyncService.syncResourceContent(entity);
        // 同步学生访问记录
        resourceStudentLogService.syncStudentLog(entity);
        // 课程助手发布消息
        assistantListen.releaseCourseResource(entity.getId(), AssistantMessageTypeEnum.INTERACTIVE_VIDEO);

        //同步班级
        List<CourseResourceEntity> list = resourceSyncService.syncClass(entity);
        //同步班级试题
        if (CollectionUtils.isNotEmpty(list)) {
            LambdaQueryWrapper<CourseResourcePartEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CourseResourcePartEntity::getContentId, entity.getId());
            List<CourseResourcePartEntity> partList = resourcePartManager.list(wrapper);
            List<Long> contentIds = list.stream().map(v -> v.getId()).collect(Collectors.toList());
            this.saveBatchQuestions(partList, entity.getVideos(), contentIds);
        }
    }

    /**
     * 下载互动视频文件
     * @param downloadDto 下载资料实体
     * @return Boolean
     * @author dzy
     */
    @Override
    public List<String> downResource(DownloadDTO downloadDto) {

        // 获取学生主信息
        Long userId = LoginHelper.getUserId();
        ClassStudentResultDTO mainStudent = R.as(classStudentClient.findVirtualClassStudentByClassIdAndUserId(downloadDto.getClassId(), userId));

        //更新资料下载次数
        if (Objects.nonNull(downloadDto) && CollectionUtils.isNotEmpty(downloadDto.getIds())
            && downloadDto.getIds().size() > 0) {
            List<Long> ids = downloadDto.getIds();
            for (Long id : ids) {
                LambdaUpdateWrapper<CourseResourceStudentLogEntity> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(CourseResourceStudentLogEntity::getContentId, id);
                updateWrapper.eq(CourseResourceStudentLogEntity::getStudentId, mainStudent.getStudentId());
                CourseResourceStudentLogEntity studentLogEntity = resourceStudentLogManager.getOne(updateWrapper);
                if (Objects.nonNull(studentLogEntity)) {
                    CourseResourceStudentLogEntity newLogEntity = new CourseResourceStudentLogEntity();
                    Integer count = studentLogEntity.getDownloadNum() == null ? 0 : studentLogEntity.getDownloadNum();
                    newLogEntity.setDownloadNum(count + 1);
                    resourceStudentLogManager.update(newLogEntity, updateWrapper);
                }
            }
        } else {
            CommonErrors.BAD_REQUEST.check(false, "没有可下载的资料信息");
        }
        List<String> downList = courseResourceBaseService.getDownPaths(downloadDto);
        return downList;
    }

    /**
     * 获取互动视频详情
     * @param contentId 资料ID
     * @return ResourceResponseDTO 返回详情对象
     * @author dzy
     */
    @Override
    public ResourceResponseDTO getResourceInfo(Long contentId) {

        // 获取互动视频数据
        ResourceResponseDTO responseDTO = courseResourceBaseManager.getResourceInfo(contentId);
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(responseDTO), MessageUtils.message("course.resource.data.id.not.exit"));

        // 获取所属章节
        if (Objects.nonNull(responseDTO.getChapterId())) {
            String chapterName = R.as(courseChapterClient.selectName(responseDTO.getChapterId()));
            responseDTO.setChapterName(chapterName);
        }

        // 获取访问用户信息
        Long userId = LoginHelper.getUserId();
        // 获取学生主信息
        ClassStudentResultDTO mainStudent = R.as(classStudentClient.findVirtualClassStudentByClassIdAndUserId(responseDTO.getClassId(), userId));

        // 不为空 则为学生
        if (Objects.nonNull(mainStudent)) {
            //更新学习学习记录
            LambdaQueryWrapper<CourseResourceStudentLogEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CourseResourceStudentLogEntity::getContentId, contentId);
            queryWrapper.eq(CourseResourceStudentLogEntity::getStudentId, mainStudent.getStudentId());
            CourseResourceStudentLogEntity studentLogEntity = resourceStudentLogManager.getOne(queryWrapper);

            // 判断 互动视频是否已结束 未结束更新状态
            if (responseDTO.getEndTime().isAfter(LocalDateTime.now())) {
                // 更新学生学习状态
                studentLogEntity = this.refreshStudentLog(mainStudent.getStudentId(), studentLogEntity, responseDTO);
            }

            // 给返回值付 新的状态
            if (Objects.nonNull(studentLogEntity)) {
                responseDTO.setStudyProgress(studentLogEntity.getStudyProgress());
                responseDTO.setStudyDuration(studentLogEntity.getStudyDuration());
                responseDTO.setStudyStatus(studentLogEntity.getStudyStatus());
            } else {
                responseDTO.setStudyProgress(new BigDecimal(0));
                responseDTO.setStudyDuration(new BigDecimal(0));
                responseDTO.setStudyStatus(YesNoNumberEnum.NO.getCode());
            }

        }

        return responseDTO;
    }

    /**
     * 更新学生学习状态
     * @author dzy
     */
    private CourseResourceStudentLogEntity refreshStudentLog(Long studentId, CourseResourceStudentLogEntity studentLogEntity, ResourceResponseDTO responseDTO) {
        if (Objects.nonNull(studentLogEntity)) {
            // 有记录进行记录更新
            LambdaUpdateWrapper<CourseResourceStudentLogEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(CourseResourceStudentLogEntity::getContentId, responseDTO.getId());
            updateWrapper.eq(CourseResourceStudentLogEntity::getStudentId, studentId);
            studentLogEntity.setIsRead(CourseContentReadEnum.READED.getCode());
            studentLogEntity.setReadNum(studentLogEntity.getReadNum() + 1);
            if (Objects.equals(CourseResourseStudyStatusEnum.UNSTUDIED.getCode(), studentLogEntity.getStudyStatus())) {
                studentLogEntity.setStudyStatus(CourseResourseStudyStatusEnum.STUDYING.getCode());
            }
            // 已结束不做更新
            if (responseDTO.getEndTime().isAfter(LocalDateTime.now())) {
                resourceStudentLogManager.update(studentLogEntity, updateWrapper);
            }
        } else {
            // 没有记录生成新的学习记录
            studentLogEntity = new CourseResourceStudentLogEntity();
            studentLogEntity.setClassId(responseDTO.getClassId());
            studentLogEntity.setStudentId(studentId);
            studentLogEntity.setContentId(responseDTO.getId());
            studentLogEntity.setContentType(responseDTO.getContentType());
            studentLogEntity.setStudyStatus(CourseResourseStudyStatusEnum.STUDYING.getCode());
            studentLogEntity.setIsRead(CourseContentReadEnum.READED.getCode());
            studentLogEntity.setReadNum(1);
            // 已结束不做更新
            if (responseDTO.getEndTime().isAfter(LocalDateTime.now())) {
                resourceStudentLogManager.save(studentLogEntity);
            }
        }
        return studentLogEntity;
    }

    /**
     * 更新互动视频学习进度
     * @param dto 资料ID
     * @author dzy
     */
    @Override
    public void refreshStudyStatus(CourseResourceVideoRefreshDTO dto) {
        // 判断是否数据存在
        CourseResourceEntity entity = Optional.ofNullable(courseResourceBaseManager.getById(dto.getContentId()))
            .orElseThrow(() -> CommonErrors.NOT_DATA.asException("course.resource.video.id.not.exit"));

        // 获取视频数据
        List<CommonFileDTO> videos = JSON.parseList(entity.getVideos(), CommonFileDTO.class);

        // 获取访问用户信息
        Long userId = LoginHelper.getUserId();
        // 获取主学生信息
        ClassStudentResultDTO student = R.as(classStudentClient.findByStudentId(entity.getClassId(), userId));
        ClassStudentResultDTO mainStudent = R.as(classStudentClient.findVirtualClassStudentByClassIdAndUserId(entity.getClassId(), userId));


        if (Objects.nonNull(student) && (Objects.equals(ClassRoleEnum.REPRESENTATIVE.getCode(), student.getClassRole())
            || Objects.equals(ClassRoleEnum.STUDENT.getCode(), student.getClassRole()))) {
            //更新学习学习记录
            LambdaQueryWrapper<CourseResourceStudentLogEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CourseResourceStudentLogEntity::getContentId, dto.getContentId());
            queryWrapper.eq(CourseResourceStudentLogEntity::getStudentId, mainStudent.getStudentId());
            CourseResourceStudentLogEntity studentLogEntity = resourceStudentLogManager.getOne(queryWrapper);
            // 判断有无历史学习记录
            if (Objects.nonNull(studentLogEntity)) {
                // 有记录-如果 学习状态已完成 不进行更行
                if (!Objects.equals(CourseResourseStudyStatusEnum.STUDIED.getCode(), studentLogEntity.getStudyStatus())) {
                    LambdaUpdateWrapper<CourseResourceStudentLogEntity> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(CourseResourceStudentLogEntity::getContentId, dto.getContentId());
                    updateWrapper.eq(CourseResourceStudentLogEntity::getStudentId, mainStudent.getStudentId());
                    studentLogEntity.setLastAccessTime(LocalDateTime.now());
                    studentLogEntity.setIsRead(CourseContentReadEnum.READED.getCode());
                    // 校验学习进度
                    this.checkStudyStatus(videos.get(0).getDuration(), studentLogEntity, dto);
                    // 已结束不做更新
                    if (entity.getEndTime().isAfter(LocalDateTime.now())) {
                        resourceStudentLogManager.update(studentLogEntity, updateWrapper);
                    }
                }
            } else {
                // 没有记录生成新的学习记录
                studentLogEntity = new CourseResourceStudentLogEntity();
                studentLogEntity.setClassId(entity.getClassId());
                studentLogEntity.setStudentId(mainStudent.getStudentId());
                studentLogEntity.setContentId(entity.getId());
                studentLogEntity.setContentType(entity.getContentType());
                studentLogEntity.setStudyStatus(CourseResourseStudyStatusEnum.STUDYING.getCode());
                studentLogEntity.setStudyDuration(new BigDecimal(0));
                studentLogEntity.setIsRead(CourseContentReadEnum.READED.getCode());
                // 校验学习进度
                this.checkStudyStatus(videos.get(0).getDuration(), studentLogEntity, dto);
                studentLogEntity.setLastAccessTime(LocalDateTime.now());
                // 已结束不做更新
                if (entity.getEndTime().isAfter(LocalDateTime.now())) {
                    resourceStudentLogManager.save(studentLogEntity);
                }
            }
        }
    }

    // 校验学习进度
    private void checkStudyStatus(BigDecimal duration, CourseResourceStudentLogEntity log, CourseResourceVideoRefreshDTO dto) {
        // 计算学习进度
        if (Objects.nonNull(dto.getStudyTime())) {
            if (log.getStudyDuration().compareTo(dto.getStudyTime()) == -1
                || log.getStudyDuration().compareTo(new BigDecimal(1)) == 1) {
                BigDecimal progress = dto.getStudyTime().divide(duration, 3, BigDecimal.ROUND_DOWN);
                log.setStudyDuration(dto.getStudyTime());
                if (progress.compareTo(new BigDecimal(1)) != -1) {
                    log.setStudyProgress(new BigDecimal(1));
                } else {
                    log.setStudyProgress(progress);
                }
            }
            // 判断学习状态 (播放总时长大于 百分之98 即播放完成)
            BigDecimal progress = log.getStudyDuration().divide(duration, 3, BigDecimal.ROUND_HALF_UP);
            if (progress.compareTo(new BigDecimal(0.98)) != -1) {
                log.setStudyStatus(CourseResourseStudyStatusEnum.STUDIED.getCode());
            } else {
                log.setStudyStatus(CourseResourseStudyStatusEnum.STUDYING.getCode());
            }
        }
    }

    /**
     * 查询互动视频统计信息
     * @param resourceQueryDTO 课程ID
     * @return List<ResourceStatisticsDTO> 集合
     * @author dzy
     */
    @Override
    public List<ResourceStatisticsDTO> resourceStatistics(ResourceQueryDTO resourceQueryDTO) {
        List<ResourceStatisticsDTO> infos = courseResourceBaseManager.resourceStatistics(resourceQueryDTO);
        infos.forEach(item -> {
            item.setStudentScore(MathUtils.stripTrailingZeros(item.getStudentScore(), 1));
        });
        return infos;
    }

    /**
     * 查询互动视频统计信息-带统计数据
     * @param resourceQueryDTO 课程ID
     * @return List<ResourceStatisticsDTO> 集合
     * @author dzy
     */
    @Override
    public ResourceStatisticsStatsDTO resourceStatisticsAll(ResourceQueryDTO resourceQueryDTO) {
        ResourceStatisticsStatsDTO result = new ResourceStatisticsStatsDTO();

        // 获取统计信息
        ResourceResponseDTO resource = getResourceInfo(resourceQueryDTO.getContentId());
        if (Objects.nonNull(resource)) {
            result.setTotal(resource.getTotal());
            result.setUnstudy(resource.getUnstudy());
            result.setStudying(resource.getStudying());
            result.setFinished(resource.getFinished());
        }

        // 获取学生列表
        List<ResourceStatisticsDTO> list = resourceStatistics(resourceQueryDTO);
        result.setList(list);

        return result;
    }

    /**
     * 学生加入班级 变更身份 同步操作
     * @param classId 班级ID
     * @param studentId 学生ID
     */
    @Override
    public void studentJoinClass(Long courseId, Long classId, Long studentId, StudentSwitchType switchType) {
        // 助教变为学生才调用同步信息
        if (!Objects.equals(StudentSwitchType.STUDENT_TO_ASSISTANT, switchType)) {
            // 获取进行中的资料库
            LambdaQueryWrapper<CourseResourceEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CourseResourceEntity::getClassId, classId);
            wrapper.eq(CourseResourceEntity::getStatus, YesNoNumberEnum.YES.getCode());
            wrapper.eq(CourseResourceEntity::getContentType, CourseContentTypeEnum.DATA.getCode());
            List<CourseResourceEntity> list = courseResourceBaseManager.list(wrapper);

            // 获取进行中的资料库学生是否已又记录
            List<Long> ids = list.stream().map(CourseResourceEntity::getId).collect(Collectors.toList());
            LambdaQueryWrapper<CourseResourceStudentLogEntity> logWrapper = new LambdaQueryWrapper<>();
            logWrapper.in(CourseResourceStudentLogEntity::getContentId, ids);
            logWrapper.eq(CourseResourceStudentLogEntity::getStudentId, studentId);
            List<CourseResourceStudentLogEntity> logList = resourceStudentLogManager.list(logWrapper);

            // 剔除已有记录的数据
            Iterator<CourseResourceEntity> iterator = list.iterator();
            while (iterator.hasNext()) {
                CourseResourceEntity entity = iterator.next();
                logList.forEach(item -> {
                    if (Objects.equals(item.getContentId(), entity.getId())) {
                        iterator.remove();
                    }
                });
            }

            // 生成未加入记录日志
            List<CourseResourceStudentLogEntity> newLogList = list.stream().map(item -> {
                CourseResourceStudentLogEntity logEntity = new CourseResourceStudentLogEntity();
                logEntity.setContentId(item.getId());
                logEntity.setClassId(item.getClassId());
                logEntity.setStudentId(studentId);
                logEntity.setContentType(item.getContentType());
                logEntity.setStudyStatus(CourseResourseStudyStatusEnum.UNSTUDIED.getCode());
                return logEntity;
            }).collect(Collectors.toList());
            resourceStudentLogManager.saveBatch(newLogList);
        }
    }

    private void setStudyStatus() {

    }

    /**
     * 保存资料文件试题
     * @author dzy
     */
    private void saveQuestions(List<CommonVideoPartDTO> partList, String videos, Long contentId) {
        // 判断是否添加互动答题
        if (CollectionUtils.isNotEmpty(partList)) {
            // 创建互动环节
            List<CourseResourcePartEntity> list = new ArrayList<>();
            partList.forEach(item -> {
                item.setContentId(contentId);
                int timeline = (int) (item.getTimePause().doubleValue()*1000);
                item.setVideoImgUrl(ResourceUtil.generateVideoImgUrl(videos,timeline));
                CourseResourcePartEntity entity = resourcePartConvert.create(item);
                if (CollectionUtils.isNotEmpty(item.getQuestions())) {
                    item.getQuestions().forEach(qItem -> {
                        if (Objects.isNull(qItem.getId()) || Objects.equals(0L, qItem.getId())) {
                            qItem.setId(identifierGenerator.nextId(null).longValue());
                        }
                    });
                }
                list.add(entity);
            });
            resourcePartService.deletePart(contentId);
            if (CollectionUtils.isNotEmpty(partList)) {
                resourcePartService.addBatchPart(list);
            }
        } else {
            resourcePartService.deletePart(contentId);
        }
    }

    /**
     * 批量保存资料文件试题
     * @author dzy
     */
    private void saveBatchQuestions(List<CourseResourcePartEntity> partList, String videos, List<Long> contentIds) {
        // 创建互动环节
        List<CourseResourcePartEntity> list = new ArrayList<>();
        contentIds.forEach(id -> {
            partList.forEach(item -> {
                CourseResourcePartEntity entity = resourcePartConvert.newEntity(item);
                entity.setId(null);
                entity.setContentId(id);
                int timeline = (int) (item.getTimePause().doubleValue()*1000);
                entity.setVideoImgUrl(ResourceUtil.generateVideoImgUrl(videos,timeline));
                list.add(entity);
            });
        });

        resourcePartService.deleteBatchPart(contentIds);
        if (CollectionUtils.isNotEmpty(partList)) {
            resourcePartService.addBatchPart(list);
        }
    }

}
